<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    label-width="120px"
    @submit.prevent="onSubmit"
  >
    <el-row :gutter="20">
      <template v-for="item in config" :key="item.prop">
        <el-col
          :span="item.layout?.span || 24"
          :xs="item.layout?.xs || 24"
          :sm="item.layout?.sm || 24"
          :md="item.layout?.md || 24"
          :lg="item.layout?.lg || 24"
          :xl="item.layout?.xl || 24"
        >
          <sno-form-item :config="item" v-model="formData[item.prop]" />
        </el-col>
      </template>
    </el-row>
    <slot name="footer" v-if="$slots.footer" />
  </el-form>
</template>
<script setup lang="ts">
import { ref, watchEffect } from "vue";
import { SFormConfig } from "@/types";
import SnoFormItem from "@/components/formItem";

const props = defineProps<{
  config: SFormConfig[];
  modelValue?: Record<string, any>;
}>();

const emit = defineEmits(["update:modelValue", "submit"]);

const formData = ref<Record<string, any>>({});
const formRules = ref<Record<string, any>>({});
// 初始化表单数据与规则
function initFormData() {
  const data: Record<string, any> = {};
  const rules: Record<string, any> = {};
  props.config.forEach((item) => {
    data[item.prop] = item.defaultValue ?? "";
    if (item.rules) {
      rules[item.prop] = item.rules;
    }
  });
  formData.value = data;
  formRules.value = rules;
}
initFormData();
// 监听 modelValue 并同步到内部
watchEffect(() => {
  if (props.modelValue) {
    Object.assign(formData.value, props.modelValue);
  }
});
function onSubmit() {
  emit("submit", formData.value);
}
</script>
